<?php

namespace app\unify\middleware;

use app\unify\traits\Result;
use Kayex\HttpCodes;
use think\facade\Log;
use think\helper\Str;
use think\Model;
use think\Paginator;
use think\Request;
use think\Response;

class ResponsePackage
{
    use Result;

    public function handle(Request $r, \Closure $next)
    {
        Log::debug("request_data" . json_encode($r->param(), JSON_UNESCAPED_UNICODE));

        /**
         * @var $response Response|string
         */
        $response = $next($r);

        $data = $response->getData();

        Log::debug("response_package_data" . json_encode($data, JSON_UNESCAPED_UNICODE));

        if (is_string($data)) {
            //如果是html直接返回
            if (preg_match("/<[^<]+>/", $data) !== 0) {
                exit($data);
            } else {
                return $this::msg($data);
            }
        } else if (is_array($data)) {
            if (isset($data['msg']) && isset($data['data']) && isset($data['code'])) {
                return $response;
            }
            return $this::data($data, $data['msg'] ?? "操作成功", $data['code'] ?? HttpCodes::HTTP_OK);
        } else if (get_parent_class($data) == Paginator::class) {
            return $this::page($data);
        } else if (is_object($data) && method_exists($data, 'toArray')){
            return $this::data($data->toArray());
        }

        return $response;
    }
}